package com.ytclub.wx.controller;

import com.ytclub.wx.constants.WxConstant;
import com.ytclub.wx.handler.WxChatMsgFactory;
import com.ytclub.wx.handler.WxChatMsgHandler;
import com.ytclub.wx.utils.MessageUtil;
import com.ytclub.wx.utils.SHA1;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

/**
 * wx回调服务控制层类
 *
 * @author: HuangQi
 * @date: Created in 22:11 2024/3/24
 * @description: wx回调服务控制器
 */
@RestController
@RequestMapping("/wx/")
@Slf4j
public class CallBackController {

    /**
     *  微信Token
     */
    private static final String TOKEN = "ytclub";

    /**
     *  分隔符 .
     */
    private static final String CACHE_KEY_SEPARATOR = ".";

    @Resource
    private WxChatMsgFactory wxChatMsgFactory;

    /**
     * 新增角色
     *
     * @param authRoleDTO 新增角色的信息
     * @return 新增结果
     */
    @RequestMapping("test")
    public String test() {
        return "hello world";
    }


    /**
     * 回调消息校验
     */
    @GetMapping("callback")
    public String callback(@RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("echostr") String echostr) {
        log.info("get验签请求参数：signature:{}，timestamp:{}，nonce:{}，echostr:{}",
                signature, timestamp, nonce, echostr);
        String shaStr = SHA1.getSHA1(TOKEN, timestamp, nonce, "");
        if (signature.equals(shaStr)) {
            return echostr;
        }
        return "unknown";
    }

    /**
     * 回调消息校验
     *
     * @return
     */
    @PostMapping(value = "callback", produces = "application/xml;charset=UTF-8")
    public String callback(
            @RequestBody String requestBody,
            @RequestParam("signature") String signature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestParam(value = "msg_signature", required = false) String msgSignature) {

        // 接收到xml信息,解析xml到map
        log.info("接收到微信消息：requestBody：\n {}", requestBody);
        Map<String, String> msgMap = MessageUtil.parseXml(requestBody);
        String msgType = msgMap.get(WxConstant.MsgType);
        String event = msgMap.get(WxConstant.EVENT) == null ? "" : msgMap.get(WxConstant.EVENT);
        log.info("接收到微信消息：\n msgType：{}，event：{} \n", msgType, event);

        // 构建微信消息类型type
        StringBuilder sb = new StringBuilder();
        sb.append(msgType);
        if (!StringUtils.isEmpty(event)) {
            sb.append(CACHE_KEY_SEPARATOR).append(event);
        }
        String msgTypeKey = sb.toString();

        // 拿取对应的消息处理类,并对消息进行处理
        WxChatMsgHandler wxChatMsgHandler = wxChatMsgFactory.getHandlerByMsgType(msgTypeKey);
        if (Objects.isNull(wxChatMsgHandler)) {
            return WxConstant.UNKNOWN_EVENT;
        }
        String replyContent = wxChatMsgHandler.dealMsg(msgMap);

        // 返回回复消息
        log.info("回复消息内容：\n{}", replyContent);
        return replyContent;
    }

}
